package uk.ac.cam.bt288.DesktopApp;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import biz.source_code.base64Coder.Base64Coder;

public class AccountManagement {
	//Method to add a new user account to the file
	public static boolean add (String username, Key k) {
		try {
			BufferedWriter out = new BufferedWriter(new FileWriter("accounts.txt", true));
			out.write(username);
			out.newLine();
			out.write( Base64Coder.encode(k.getEncoded()));
			out.newLine();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return true;
	}

	//return list of all accounts
	public static Map<Key, String> getAllAccounts () {
		Map<Key, String> m = new HashMap<Key, String>();
		try {
			BufferedReader in = new BufferedReader(new FileReader("accounts.txt"));
			String username = null;
			while ( ( username=in.readLine())  != null) {
				String key = in.readLine();
				byte[] encodedPub = Base64Coder.decode(key);
				KeyFactory rsaKeyFac = KeyFactory.getInstance("RSA");
				PublicKey pubKey = rsaKeyFac.generatePublic(new X509EncodedKeySpec(encodedPub));
				m.put(pubKey, username);
			}
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return m;
	}

}
